package com.zzyl.nursing.service.impl;

import java.lang.invoke.VarHandle;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;

import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-06
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 新增入住申请
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否入住
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
        //根据老人身份证号查询
        queryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus,1);
        Elder elder = elderService.getOne(queryWrapper);
        if(!ObjectUtils.isEmpty(elder)){
            throw new BaseException("老人已入住，不能重复入住");
        }
        //2.更新床位状态为已入住
        //根据床位id查询床位信息
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
        //3.新增或更新老人
        //获取老人家属信息
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        elder = insertOrUpdateElder(checkInElderDto, bed);
        //4.新增合同信息
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        insertContract(checkInContractDto,elder,checkInConfigDto);
        //5.新增入住信息
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        CheckIn checkIn = addCheckIn(checkInConfigDto, elder, bed,elderFamilyDtoList);
        //6.新增入住配置信息
        insertCheckInConfig(checkIn,checkInConfigDto);
    }

    /**
     * 根据id查询入住信息
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInById(Long id) {
        //1、查询入住信息
        CheckIn checkIn = getById(id);
        //2、查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //计算年龄
        String birthday = elder.getBirthday();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //将字符串转换为LocalDate
        LocalDate birthdayTime = LocalDate.parse(birthday, dateTimeFormatter);
        //计算当前时间和生日之间的时间差
        Period between = Period.between(birthdayTime, LocalDate.now());
        Integer age = between.getYears();
        checkInElderVo.setAge(age);
        //3、查询合同
        LambdaQueryWrapper<Contract> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Contract::getElderId,checkIn.getElderId());
        Contract contract = contractMapper.selectOne(queryWrapper);
        //4、查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper1);
        if(checkInConfig==null){
            throw new BaseException("入住配置信息不存在");
        }
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //5、查询老人家属信息并转化为集合
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        //6、返回
        CheckInDetailVo checkInDetailVo = CheckInDetailVo.builder()
                .checkInElderVo(checkInElderVo)
                .contract(contract)
                .checkInConfigVo(checkInConfigVo)
                .elderFamilyVoList(elderFamilyVoList)
                .build();
        return checkInDetailVo;
    }


    /**
     * 新增入住配置信息
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param checkInConfigDto
     * @param elder
     * @param bed
     *  @param elderFamilyDtoList
     */

    private CheckIn addCheckIn(CheckInConfigDto checkInConfigDto, Elder elder, Bed bed,List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkIn.setStatus(0);
        insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增合同信息
     * @param checkInContractDto
     * @param elder
     * @param checkInConfigDto
     */
    private void insertContract(CheckInContractDto checkInContractDto, Elder elder, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //生成合同编号
        String number = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(1);
        contractMapper.insertContract(contract);
    }

    /**
     * 新增或更新老人
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //创建一个老人对象并设置数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //根据老人身份证号查询
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus,1);
        Elder elderone = elderService.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(elderone)){
            //查询出来的结果为空，新增
            elderService.insertElder(elder);
        }else{
            //查询出来的结果不为空，更新
            elderService.updateElder(elder);
        }
        return elder;
    }

}
